/**
 * 格式化工具函数
 */

/**
 * 格式化时间为相对时间
 * @param {string|Date} time 时间
 * @returns {string} 格式化后的时间
 */
export const formatRelativeTime = (time) => {
  const now = new Date()
  const targetTime = new Date(time)
  const diff = now - targetTime
  
  const minute = 60 * 1000
  const hour = 60 * minute
  const day = 24 * hour
  const month = 30 * day
  const year = 365 * day
  
  if (diff < minute) {
    return '刚刚'
  } else if (diff < hour) {
    return `${Math.floor(diff / minute)}分钟前`
  } else if (diff < day) {
    return `${Math.floor(diff / hour)}小时前`
  } else if (diff < month) {
    return `${Math.floor(diff / day)}天前`
  } else if (diff < year) {
    return `${Math.floor(diff / month)}个月前`
  } else {
    return `${Math.floor(diff / year)}年前`
  }
}

/**
 * 格式化数字为简化形式
 * @param {number} num 数字
 * @returns {string} 格式化后的数字
 */
export const formatNumber = (num) => {
  if (num < 1000) {
    return num.toString()
  } else if (num < 10000) {
    return `${(num / 1000).toFixed(1)}k`
  } else if (num < 100000000) {
    return `${(num / 10000).toFixed(1)}万`
  } else {
    return `${(num / 100000000).toFixed(1)}亿`
  }
}

/**
 * 截取文本并添加省略号
 * @param {string} text 文本
 * @param {number} maxLength 最大长度
 * @returns {string} 截取后的文本
 */
export const truncateText = (text, maxLength = 100) => {
  if (!text) return ''
  if (text.length <= maxLength) return text
  return text.substring(0, maxLength) + '...'
}

/**
 * 格式化日期为 YYYY-MM-DD HH:mm 格式
 * @param {string|Date} date 日期
 * @returns {string} 格式化后的日期
 */
export const formatDateTime = (date) => {
  const d = new Date(date)
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  const hours = String(d.getHours()).padStart(2, '0')
  const minutes = String(d.getMinutes()).padStart(2, '0')
  
  return `${year}-${month}-${day} ${hours}:${minutes}`
}
